package cn.fan.springboot_easyexcle.util;

import cn.fan.springboot_easyexcle.model.UserExportVO;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * easyexl导出到压缩包的的工具类
 */

public class EasyExceltofileUtil {
    private static final Logger logger = LoggerFactory.getLogger(EasyExceltofileUtil.class);


    /**
     * 根据表头，数据，文件名称，进行exl的导出，xls格式
     *
     * @param fileName 文件名
     * @param heads    标题
     * @param alldata  实际数据
     */
    public  static  String exlport(String fileName, String filepath,  List<List<Object>> alldata,Class<? extends BaseRowModel> cls) {
       return exportfile(fileName, filepath, alldata, ".xlsx", ExcelTypeEnum.XLSX,cls);
    }

    public  static  void exlport(String filenames,HttpServletResponse response, List<List<Object>> alldata, Class<? extends BaseRowModel> cls) throws IOException {


        try {
            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
//            response.addHeader("Content-Disposition", URLEncoder.encode(filenames, "utf-8")  + ".xlsx");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(filenames, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//            第一种方式
//            WriteSheet[] writeSheet = new WriteSheet[]{
//                    EasyExcel.writerSheet(0, "sheet").build()
//            };
//            ExcelWriter  excelWriter = EasyExcel.write(response.getOutputStream(), cls).build();
//            excelWriter.write(alldata,writeSheet[0]);
//            excelWriter.finish();
//// 这里需要设置不关闭流  第二种
            EasyExcel.write(response.getOutputStream(), cls).autoCloseStream(Boolean.FALSE).sheet("sheet")
                    .doWrite(alldata);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }

    }
    private  static  String exportfile(String fileName, String filepath,  List<List<Object>> alldata, String filetype, ExcelTypeEnum exltype,Class<? extends BaseRowModel> cls) {
        FileOutputStream fos = null;
        String filespathresult="";
        try {
             filespathresult=filepath +File.separator + fileName+getnowtime() + filetype;
            //如果文件夹不存在就创建文件夹
            File folder = new File(filepath);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdirs();
            }
            File file = new File(filespathresult);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            ExcelWriter writer = EasyExcelFactory.getWriter(fos, exltype, true);

            // 动态添加表头，适用一些表头动态变化的场景
            com.alibaba.excel.metadata.Sheet sheet1 = new com.alibaba.excel.metadata.Sheet(1, 0,cls);
            sheet1.setSheetName("sheet1");
            // 写数据
            writer.write1(alldata, sheet1);
            // 将上下文中的最终 outputStream 写入到指定文件中
            writer.finish();
        } catch (Exception e) {
            logger.error("导出exl失败" + fileName, e);
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filespathresult;
    }

    private static String getnowtime(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(new Date());
        return dateString;
    }

}
